package com.ophiux.wechatpay.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {
	protected static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
	private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
	public static String HTTP_POST = "POST";
	public static String HTTP_GET = "GET";

	/**
	 * 
	 * @param requestUrl
	 * @param requestMethod
	 * @param outputStr
	 * @return
	 * @throws Exception
	 */
	public static String httpsRequest(String requestUrl, String requestMethod,
			String outputStr) throws Exception {
		return httpsRequest(requestUrl, requestMethod, outputStr, 30 * 1000);
	}
	
	public static String doPost(String requestUrl,String paramJson) throws Exception {
		StringBuffer resultContent = new StringBuffer();
		URL url = new URL(requestUrl);
		HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
		//连接超时设为30秒，读取数据超时设为30秒
		httpUrlConn.setConnectTimeout(50*1000);
		httpUrlConn.setReadTimeout(50*1000);
		httpUrlConn.setDoOutput(true);
		httpUrlConn.setDoInput(true);
		httpUrlConn.setUseCaches(false);
//			httpUrlConn.setRequestProperty("Content-type","application/x-java-serialized-object");
		//httpUrlConn.setRequestProperty("Content-type","application/soap+xml; charset=utf-8");
		httpUrlConn.setRequestProperty("Content-type","application/json");
		// 设定请求的方法为"POST"，默认是GET
		httpUrlConn.setRequestMethod("POST");
		System.out.println("请求参数："+paramJson);
		InputStream inputStream = null;
		try {
			if (null != paramJson) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(paramJson.getBytes("UTF-8"));
				outputStream.close();
			}
			// 将返回的输入流转换成字符串
			inputStream = httpUrlConn.getInputStream();

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				resultContent.append(str);
			}
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
					inputStream = null;
				}
				httpUrlConn.disconnect();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return	resultContent.toString();
	}

	/**
	 * 
	 @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式
	 * @param outputStr
	 * @param timeout
	 *            超时时间
	 * @return
	 * @throws Exception
	 */
	public static String httpsRequest(String requestUrl, String requestMethod,
			String outputStr, int timeout) throws Exception {

		StringBuffer buffer = null;
		try {
			URL url = new URL(requestUrl);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(requestMethod);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(timeout);
			conn.connect();
			if (outputStr != null) {
				OutputStream os = conn.getOutputStream();
				os.write(outputStr.getBytes("utf-8"));
				os.close();
			}

			InputStream is = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(isr);

			buffer = new StringBuffer();
			String line = null;

			while ((line = br.readLine()) != null) {
				buffer.append(line);
			}

		} catch (Exception e) {
			throw e;
		}
		return buffer.toString();
	}

	public static String post(final String url, final String param) {
		Callable callable = new Callable<String>() {
			public String call() throws Exception {
				return HttpUtil.sendPost(url, param);
			}
		};
		Future<String> temp = fixedThreadPool.submit(callable);
		try {
			return temp.get();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			conn.setConnectTimeout(10000);
			// 设置通用的请求属性
			conn.setRequestProperty("user-agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			OutputStreamWriter outWriter = new OutputStreamWriter(
					conn.getOutputStream(), "utf-8");
			out = new PrintWriter(outWriter);
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				in = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
	
	public static String[] httpGetRequest(String url, String param) {
    	String[] returnValues = new String[2];
    	//是否调用成功
    	String isSucc = "true";
        StringBuffer result = new StringBuffer("");
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            logger.info("请求链接：------"+urlNameString);
            System.out.println("完整请求链接--------------------------------------------"+urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
           
            // 建立实际的连接 
            connection.connect();
            // 获取所有响应头字段
           /* Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }*/
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            isSucc = "false";//调用失败
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
        		 returnValues[0] = result.toString();
        		 returnValues[1] = isSucc;
            try {
                if (in != null) {
                    in.close();
                }
	            } catch (Exception e2) {
	                e2.printStackTrace();
	            }
        }
        return returnValues;
    }

}
